package com.example.auth.config;

import com.alibaba.fastjson.JSONObject;
import com.example.auth.domain.OauthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.SimpleFormatter;

@Component
@Slf4j
public class CustomAuthenticationProvider implements AuthenticationManager {

    private final UserDetailsService userDetailsService;

    private final PasswordEncoder passwordEncoder;

    private final AuthenticationProvider authenticationProvider;


    public CustomAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder,AuthenticationProvider authenticationProvider) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
        this.authenticationProvider=authenticationProvider;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("开始登录{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if(authentication==null || authentication.getDetails()==null ){
            throw new BadCredentialsException("登录信息不得为空");
        }
        if(authentication.getPrincipal()==null){
            throw new BadCredentialsException("登录账号不得为空");
        }
        OauthUser details=(OauthUser)userDetailsService.loadUserByUsername(authentication.getPrincipal().toString());
        if(details==null){
            throw new BadCredentialsException("用户账号或密码错误");
        }
        Map<String,Object> map=(Map<String, Object>) authentication.getDetails();
        log.info(JSONObject.toJSONString(map));
        if(isEmpty(map,"code")){
            throw new BadCredentialsException("验证码不得为空");
        }
        if(authentication.getCredentials()==null){
            throw new BadCredentialsException("登录密码不得为空");
        }
        String password=passwordEncoder.encode(authentication.getCredentials().toString());
        if(!passwordEncoder.matches(authentication.getCredentials().toString(),details.getPassword())){
            throw new BadCredentialsException("用户账号或密码错误2");
        }
        log.info(JSONObject.toJSONString(authentication.getPrincipal()));
        // 创建自定义 Authentication，包含额外信息
        return new CustomAuthenticationToken(
                authentication.getPrincipal().toString(),
                null,
                details.getUserId(),details.getAuthorities());
    }


    private boolean isEmpty(Map<String,Object> map,String key){
        return map.get(key)==null || map.get(key).toString().trim().isEmpty();
    }

}
